package com.qigao.mall.channel.weichat;

import com.alibaba.fastjson.JSONObject;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.commons.enums.ChannelCodeEnum;
import com.qigao.mall.commons.param.ChannelRespParam;
import com.qigao.mall.commons.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class WeiChatGetCertficates {

    public ChannelRespParam getCertficates(){
        try {
            String requestParam = buildReqParam();
            log.info("微信进件获取密钥序列号，请求参数：【{}】",requestParam);
            String responeParam=HttpClientUtil.doPostStr("https://api.mch.weixin.qq.com/risk/getcertficates",requestParam);
            log.info("微信进件获取密钥序列号，返回参数：【{}】",responeParam);
            if (StringUtils.isBlank(responeParam)) return ChannelRespParam.error("获取密钥序列号失败");
            Map<String,String> respMap=WXPayUtil.xmlToMap(responeParam);
            if ("SUCCESS".equals(respMap.get("return_code"))&&"SUCCESS".equals(respMap.get("result_code"))){
                //获取密钥序列号
                String serial_no=JSONObject.parseObject(respMap.get("certificates")).getJSONArray("data").getJSONObject(0).getString("serial_no");
                return ChannelRespParam.success(serial_no,"获取成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ChannelRespParam.error("获取密钥序列号失败");
    }

    private String buildReqParam() throws Exception {
        Map commonReqParam=new ConcurrentHashMap<>();
        commonReqParam.put("mch_id","1578082901");//商户号
        commonReqParam.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串4C7CDE1A8E7C93347E6C6F1DFEA95304D57AD9A3
        commonReqParam.put("sign_type","HMAC-SHA256");//签名方式
        String signValue= WXPayUtil.generateSignature(commonReqParam,"3386ead9287e2f9e78B507F7C0D4D281", WXPayUtil.SignType.HMACSHA256);
        commonReqParam.put("sign",signValue);
        //返回请求微信方的xml参数
        return PayUtil.mapToXml(commonReqParam);
    }

    public static void main(String[]args){
        WeiChatGetCertficates chatGetCertficates=new WeiChatGetCertficates();
        chatGetCertficates.getCertficates();
        //FD29B578B31C509B45B7C2779803D9E41B68E6B84AEB1EBDE47DCA00049B649B
        //99EA32BA5C8F341FF32FF2E15BF4CAFFE19A6CF3EC8E9557EDE6D8ED919A0EFD
    }
}
